/*
 * Thread.cpp
 *
 *  Created on: Sep 10, 2011
 *      Author: Gherman Alin
 */

#include "Thread.h"

namespace Threads {

Thread::Thread() :
		thisThread(NULL), target(NULL) {
}

Thread::Thread(Runnable* _target) :
		thisThread(NULL), target(_target) {
}

Thread::~Thread() {
	if (NULL != thisThread) {
		throw ThreadUsageException(
				"Must call join() before the destruction of a thread object. This can be done in the TOP destructor.");
	}
}

void Thread::start() {
	boost::mutex::scoped_lock l(thisMutex);
	if (NULL != thisThread) {
		return;
	}
	thisThread = new boost::thread(&Thread::run, this);
}

void Thread::run() {
	if (NULL != target) {
		target->run();
	}
}

void Thread::join() {
	boost::mutex::scoped_lock l(thisMutex);
	if (NULL != thisThread) {
		thisThread->join();
		delete thisThread;
		thisThread = NULL;
	}
}

}
